package cn.edu.hit.education.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import cn.edu.hit.education.pojo.Course;
import cn.edu.hit.education.pojo.Property;
import cn.edu.hit.education.pojo.Specialty;
import cn.edu.hit.education.pojo.User;
import cn.edu.hit.education.service.ICourseService;
import cn.edu.hit.education.service.IPropertyService;
import cn.edu.hit.education.service.ISpecialtyService;
import cn.edu.hit.education.service.IUserSpeciatyService;
import cn.edu.hit.education.service.SpecialtyServiceImpl;
import cn.edu.hit.education.service.UserSpeciatyServiceImpl;
import educationschedule.Activator;
import educationschedule.Application;

public class ExportAction extends Action {
	ICourseService courseService = (ICourseService)Application.applicationContext.getBean("courseServiceImpl");
	IPropertyService propertyService = (IPropertyService)Application.applicationContext.getBean("propertyServiceImpl");
	IUserSpeciatyService userSpeciatyService = Application.applicationContext.getBean(UserSpeciatyServiceImpl.class);
	ISpecialtyService specialtyService = Application.applicationContext.getBean(SpecialtyServiceImpl.class);
	
	public ExportAction(){
		this.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/toolbar/export_16px.png"));
		this.setToolTipText("导出课程");
		this.setText("导出课程");
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Specialty specialty = new Specialty();
		List<Specialty> specialties = new ArrayList<>();
		
		//根据普通用户的用户Id查询到关联的专业Id
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		List<Integer> ids = userSpeciatyService.querySpeciatyIdsByUser(user.getId());
		specialties = specialtyService.queryRelativeSpecialty(ids);	
		
		specialty.setName(specialties.get(0).getName());
		
		Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		FileDialog fileDialog = new FileDialog(parentShell,SWT.SAVE);
		fileDialog.setFilterExtensions(new String[]{"*.xls"});
		String filename ;
		filename = fileDialog.open();
		if(filename != null){
			List<Property> properties = propertyService.queryAllProperty();
			List<String> strProperties = new ArrayList<String>();
			if(properties != null && properties.size() > 0){
				for (Property property : properties) {
					strProperties.add(property.getName());
				}
			}
			List<String> strUnit = new ArrayList<String>();
			strUnit.add("时");
			strUnit.add("周");
			List<String> strImportant = new ArrayList<String>();
			strImportant.add("是");
			strImportant.add("否");
			List<String> strSelected = new ArrayList<String>();
			strSelected.add("必修课");
			strSelected.add("选修课");
			List<String> strMethod = new ArrayList<String>();
			strMethod.add("集中");
			strMethod.add("分散");
			strMethod.add("项目");
			List<String> strClassroom = new ArrayList<String>();
			strClassroom.add("授课");
			strClassroom.add("讲座");
			
			List<Course> courses = courseService.queryAllCourse();
			Map<String, String> courserPropertyMap = getMap(courses, properties);//课程与课程属性的映射关系
			
			
			try {
				test(courserPropertyMap,filename,specialty,
						String.join(",", strProperties),String.join(",", strImportant),
						String.join(",", strUnit), String.join(",",strSelected),
						String.join(",",strMethod),	String.join(",",strClassroom),
						courses);
				
				MessageBox messageBox=new MessageBox(parentShell,SWT.OK|SWT.ICON_INFORMATION);
				 messageBox.setText("提示！");
				 messageBox.setMessage("导出成功！");
				 messageBox.open();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		super.run();
	}
	
	  public void test(Map<String,String> courserPropertyMap,String filename,Specialty specialty,
			  String strProperties,String strImportant,
			  String strUnit,String strSelected,
			  String strMethod,String strClassRoom,
			  List<Course> courses) throws IOException {
	        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
	        HSSFSheet sheet = hssfWorkbook.createSheet();
	        HSSFRow row = sheet.createRow(0);
	        row.createCell(0).setCellValue("专业名称");
	        row.createCell(1).setCellValue("课程性质");
	        row.createCell(2).setCellValue("课程名称");
	        row.createCell(3).setCellValue("课程学分");
	        row.createCell(4).setCellValue("是否核心");
	        row.createCell(5).setCellValue("课程编号");
	        row.createCell(6).setCellValue("课程学时");
	        row.createCell(7).setCellValue("理论学时");
	        row.createCell(8).setCellValue("实验学时");
	        row.createCell(9).setCellValue("学时单位");
	        row.createCell(10).setCellValue("课程选修");
	        row.createCell(11).setCellValue("授课类型");
	        row.createCell(12).setCellValue("授课方式");
	        row.createCell(13).setCellValue("开始时间");
	        row.createCell(14).setCellValue("结束时间");
	        row.createCell(15).setCellValue("课程备注");
			
	        //////////////////////////////////////////////////
	        String colProperty = "KCXZ";   //课程性质
	        Map<String, String> boxMapProperty = new HashMap<>();
	        boxMapProperty.put(colProperty, strProperties);
	        HSSFDataValidation dataValidationProperty = createBox(colProperty, boxMapProperty , 1 , courses.size()+1 , 1 , 1);
	        if(dataValidationProperty != null) {
	            sheet.addValidationData(dataValidationProperty);
	        }
			//////////////////////////////////////////////////
			String colImportant = "KSZY";   
			Map<String, String> boxMapImportant = new HashMap<>();
			boxMapImportant.put(colImportant, strImportant);
			HSSFDataValidation dataValidationImportant = createBox(colImportant, boxMapImportant , 1 , courses.size()+1 , 4 , 4);
			if(dataValidationImportant != null) {
				sheet.addValidationData(dataValidationImportant);
			}
			//////////////////////////////////////////////////
			String colUnit = "KSDW"; 
			Map<String, String> boxMapUnit = new HashMap<>();
			boxMapUnit.put(colUnit, strUnit);
			HSSFDataValidation dataValidationUnit = createBox(colUnit, boxMapUnit , 1 , courses.size()+1 , 9 , 9);
			if(dataValidationUnit != null) {
				sheet.addValidationData(dataValidationUnit);
			}
	        //////////////////////////////////////////////////
	        String colSelected = "KCXX";  
	        Map<String, String> boxMapSelected = new HashMap<>();
	        boxMapSelected.put(colSelected, strSelected);
	        HSSFDataValidation dataValidationSelected = createBox(colSelected, boxMapSelected , 1 , courses.size()+1 , 10 , 10);
	        if(dataValidationSelected != null) {
	            sheet.addValidationData(dataValidationSelected);
	        }
	        //////////////////////////////////////////////////
	        String colMethod = "SKLX"; 
	        Map<String, String> boxMapMethod = new HashMap<>();
	        boxMapMethod.put(colMethod, strMethod);
	        HSSFDataValidation dataValidationMethod = createBox(colMethod, boxMapMethod , 1 , courses.size()+1 , 11 , 11);
	        if(dataValidationMethod != null) {
	            sheet.addValidationData(dataValidationMethod);
	        }
	        ///////////////////////////////////////////////////
	        String colClassroom = "SKFS";  
	        Map<String, String> boxMapClassroom = new HashMap<>();
	        boxMapClassroom.put(colClassroom, strClassRoom);
	        HSSFDataValidation dataValidationClassroom = createBox(colClassroom, boxMapClassroom , 1 , courses.size()+1 , 12 , 12);
	        if(dataValidationClassroom != null) {
	            sheet.addValidationData(dataValidationClassroom);
	        }
	        ///////////////////////////////////////////////////
	        
	        for (int i = 0;i < courses.size();i++) {
	        	Course theCourse = courses.get(i);
	        	HSSFRow newRow = sheet.createRow(i + 1);
	        	newRow.createCell(0).setCellValue(specialty.getName());
	        	newRow.createCell(1).setCellValue(courserPropertyMap.get(theCourse.getName()));
	        	newRow.createCell(2).setCellValue(theCourse.getName());
	        	newRow.createCell(3).setCellValue(String.valueOf(theCourse.getCredits()));
	        	newRow.createCell(4).setCellValue(String.valueOf((theCourse.getImportant() == 1?"是":"否")));
	        	newRow.createCell(5).setCellValue(theCourse.getNumber());
	        	newRow.createCell(6).setCellValue(String.valueOf(theCourse.getPeriod()));
	        	newRow.createCell(7).setCellValue(String.valueOf(theCourse.getTheoretical()));
	        	newRow.createCell(8).setCellValue(String.valueOf(theCourse.getExperiment()));
	        	newRow.createCell(9).setCellValue(String.valueOf(theCourse.getUnit()));
	        	newRow.createCell(10).setCellValue(String.valueOf(theCourse.getSelected()));
	        	newRow.createCell(11).setCellValue(String.valueOf(theCourse.getMethod()));
	        	newRow.createCell(12).setCellValue(String.valueOf(theCourse.getClassroom()));
	        	newRow.createCell(13).setCellValue("1");
	        	newRow.createCell(14).setCellValue("16");
	        	newRow.createCell(15).setCellValue("");
			}
	        ///////////////////////////////////////////////////
	        FileOutputStream out = new FileOutputStream(filename);
	        hssfWorkbook.write(out);
	        out.close();
	    }
	  
	  /**
	   * 获取课程和课程属性的映射关系
	   * <p>Title: getMap</p>  
	   * <p>Description: </p>  
	   * @param courses
	   * @param properties
	   * @return
	   */
	  public Map<String,String> getMap(List<Course> courses,List<Property> properties){
		  HashMap<String, String> coursePropertyMap = new HashMap<>();
			for(Course course : courses){
				for(Property property :properties){
					if(property.getId() == course.getPropertyId()){
						coursePropertyMap.put(course.getName(), property.getName());
					}
				}
			}
			return coursePropertyMap;
		  
	  }

	    public HSSFDataValidation createBox(String col, Map<String , String> boxMap, 
	    		int firstRow, int lastRow, int firstCol, int lastCol) {
	        HSSFDataValidation dataValidation = null;
	        String cols = "";
	        if(null != boxMap.get(col)) {
	            cols = boxMap.get(col);
	        }
	        if(cols.length() > 0 && null != cols) {
	            String str[] = cols.split(",");
	            CellRangeAddressList cas = new CellRangeAddressList(firstRow , lastRow , firstCol , lastCol);
	            DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(str);
	            dataValidation = new HSSFDataValidation(cas, dvConstraint);
	        }
	        return dataValidation;
	    }

	

}
